package com.fjut.kms.tools;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * Created by Empathy on 2017/7/11.
 */
public class RsaKey {
    public PublicKey publicKey=null;
    public  PrivateKey privateKey=null;
    public String publicKeyModulus=null;
    public static String publicKeyStr="<RSAKeyValue><Modulus>oeCSKnNiONS7OMcjUnVs5NT4v7tloG+jkBxArXw5Ow5oHDEFM6RbL9BwVAPzDXymsOvMA7IoIjWiafgKI/zQJakBhdslbK6U66SZ+J7jSSuwNkbtW4NgM8GaMy7u7zkPp15Yg7hmMENvLM0pwA2GfiIr6sk52aMvdYpJwUiY9qE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
    public int pkLen=0;
    public static String privateKeyXml="<RSAKeyValue><Modulus>oeCSKnNiONS7OMcjUnVs5NT4v7tloG+jkBxArXw5Ow5oHDEFM6RbL9BwVAPzDXymsOvMA7IoIjWiafgKI/zQJakBhdslbK6U66SZ+J7jSSuwNkbtW4NgM8GaMy7u7zkPp15Yg7hmMENvLM0pwA2GfiIr6sk52aMvdYpJwUiY9qE=</Modulus><Exponent>AQAB</Exponent><P>5IKYjmlQ7k8MEQelgS/tqch73Ai1K3oiryELc4Tz3dClZOJET3xWPUqjaH73dYl+wj6BBvPICbqTEAPPor5t+w==</P><Q>tVnjT3RT3AdKVgW9t3WDHxu1dnJLZF/Lxan3MOSiBmtWFSd2tMTSQsR8Wqg6kcYfzdzmZJtOSTvwGOd3g/vXEw==</Q><DP>lpXJWu/kOWc2GHLlikC/aceId/P1D/WoraglF7dhzacVl2nUglz5p+Jr1Qz2nipBslfmR2KXTHH7P+6DAkhjyQ==</DP><DQ>bm6CQQvxVPcLiT6NvH3Ojs7svWf0CPdcus05PYi8MXSDQvZ5DrMb5pSHtRzkLYicLVvq4DDCh038cu3glXpyCQ==</DQ><InverseQ>k7+yytgt3Ca6UP+tfOpUzIrJXcEEM5ijJ9SliBke1+SjpLIRV6gk2ZGM0iopA7VECENHHFhGTQnxRk9nTWX8AQ==</InverseQ><D>GtJmBaimrrn455h/bstMJsJvEP3RAftdg6RaxyQdK37gm0M4FG14Onz0D8ezvxlXWVtIq5gadEikx6A0te/O4RqtTXFtMl7MS9gt8hdFyhPcsDl8tTtClTr73ZQmMj4O8J1cvH604AtsX9y3vaaj8vl1yP59K+2f8fFWQTBZgN0=</D></RSAKeyValue>";
    //创建公钥，私钥以及发给客户端的公钥字符串
    /********************************
     *
     * @param prkey
     * @param str_en
     * @return
     */
    public  String decrypt(PrivateKey prkey,String str_en) throws Exception
    {
        String result="",temp;
        byte[] ary_en;
        byte[] deBytes ;
        //注意Cipher初始化时的参数“RSA/ECB/PKCS1Padding”,代表和.NET用相同的填充算法，如果是标准RSA加密，则参数为“RSA”
        Cipher cipher = Cipher.getInstance("RSA/None/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, prkey);
        while(str_en.length()>0)//分段解密，每段长度为公钥长度
        {
            if(str_en.length()>this.pkLen)
            {
                temp=str_en.substring(0,this.pkLen );
                str_en=str_en.substring(this.pkLen );
            }
            else
            {
                temp=str_en;
                str_en="";
            }
            ary_en=(new BASE64Decoder()).decodeBuffer(temp);
            deBytes = cipher.doFinal(ary_en);
            String s = new String(deBytes );
            result=result+s;
        }


        return result;

    }
    //公钥长度为172，每172个字符解压
    public  String decrypt2(String str_en) throws Exception
    {
        PrivateKey priKey = RsaHelper.decodePrivateKeyFromXml(RsaKey.privateKeyXml);
        String decryptedStr;
        byte[] encryptedData= Base64Helper.decode(str_en);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] cache;
        // 对数据分段解密
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String tmp;
        while (str_en.length()>0) {
            if(str_en.length()>172)
            {
                tmp=str_en.substring(0,172);
                str_en=str_en.substring(172);
            }
            else
            {
                tmp=str_en;
                str_en="";
            }
            encryptedData= Base64Helper.decode(tmp);
            cache=cipher.doFinal(encryptedData);
            out.write(cache, 0, cache.length);

        }
        byte[] decryptedData = out.toByteArray();
        decryptedStr=new String(decryptedData, "utf-8");
        out.close();
        return decryptedStr;
    }
}
